﻿/* $RCSFile: CrmUtil4ISV.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/CRMWrapper3/CrmUtil4ISV.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:31  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.Services.Protocols;
using System.Globalization;

using CrmSdk.CRM4;

using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.CRM4Server;
using AddonNice.CRMWrapper.CRM4Meta;

namespace AddonNice.CRMWrapper
{

        public class XmlValidator
        {

            XmlSchema _schema;
            StringBuilder _messages;

            public XmlValidator(string schemaUri)
            {
                using (XmlReader reader = new XmlTextReader(schemaUri))
                {
                    _schema = XmlSchema.Read(reader, null);
                }
            }

            public string Validate(string xml)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                return this.Validate(doc);
            }

            public string Validate(XmlDocument doc)
            {
                _messages = new StringBuilder();
                doc.Schemas.Add(_schema);
                doc.Validate(new ValidationEventHandler(ValidationCallBack));

                return _messages.ToString();
            }

            private void ValidationCallBack(object sender, ValidationEventArgs e)
            {
                _messages.AppendLine(e.Message);
            }

            /// <summary>
            /// FormatXml takes any valid XML content and formats it like IE or Visual Studio does. 
            /// </summary>
            /// <param name="xml"></param>
            /// <returns></returns>
            static public string FormatXml(string xml) 
            {
                StringBuilder sb            = new StringBuilder();
                XmlWriterSettings settings  = new XmlWriterSettings();
                settings.Indent             = true;
                settings.IndentChars        = " ";
                settings.OmitXmlDeclaration = true;

                using (XmlWriter w = XmlTextWriter.Create(sb, settings)) 
                {
                    using (TextReader tr = new StringReader(xml)) 
                    {
                        using (XmlReader r = XmlTextReader.Create(tr)) 
                        {
                            w.WriteNode(r, true);
                        }
                    }
                }
                return sb.ToString();
            }
        }
    
    /// <summary>
    /// Toolkit to modify CRM SiteMap
    /// Add an Button
    /// Add an Area
    /// Import/Export datas
    /// </summary>
    public class CrmUtil4ISV
    {
        #region metadata management

        protected string _DataXml       =   string.Empty;
        public string DataXml           
        {
            get { return _DataXml; }
            set { _DataXml = value; }
        }
        
        protected XmlDocument _metadata =   new XmlDocument();
        
        public XmlDocument Metadata
        {
            get { return _metadata; }
            set { _metadata = value; }
        }

        #endregion metadata management

        #region properties

        CrmWrapper4 _wrapper   =   null;
        CrmWrapper4 wrapper
        {
            get
            {
                return _wrapper;
            }
        }

        #region output/output values to set before or automatically selected 

        string _errMsg  =   string.Empty;
        public string errMsg
        {
            get
            {
                return _errMsg;
            }
        }

        string _LCID    = System.Threading.Thread.CurrentThread.CurrentCulture.LCID.ToString();
        public string LCID
        {
            get
            {
                return _LCID;
            }
        }


        #endregion output/output values to set before or automatically selected 
        
        #endregion properties

        #region Ctor

        public CrmUtil4ISV(CrmWrapper4 wrap)
        {
            _wrapper        =   wrap;
        }

        #endregion Ctor

        #region public methods


        public XmlNode ISvConfig
        {
            get
            {
                string path = "//ImportExportXml/IsvConfig";
                return _metadata.SelectSingleNode(path);
            }
        }

        /// <summary>
        /// Export from Crm ISV Datas in DataXml property of this object
        /// </summary>
        public string ExportXml()
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]CrmUtil4ISV ExportXml BEG .",CRMTraceSwitch.Sw.Info);
            ImportExportXml ImportExportData    =   new ImportExportXml(ImportExportType.isvconfigxml);
            bool ret                            =   ImportExportData.Export(wrapper);
            if ( ret)
            {
                DataXml                         =   ImportExportData.DataXml;
                Metadata.LoadXml(DataXml);
            }
            else _errMsg                        =   ImportExportData.strErr;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV ExportXml END ret: {0}", ret),CRMTraceSwitch.Sw.Info);
            return DataXml;
        }

        /// <summary>
        /// Import into Crm ISV Datas from DataXml property of this object
        /// </summary>
        public string ImportXml(bool publish)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV ImportXml BEG publish: {0}.",publish),CRMTraceSwitch.Sw.Info);
            ImportExportXml ImportExportData    =   new ImportExportXml(ImportExportType.isvconfigxml,DataXml);
            bool ret                            =   ImportExportData.Import(wrapper,publish);
            if ( !ret )
                _errMsg                         =   ImportExportData.strErr;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV ImportXml END ret: {0}", ret),CRMTraceSwitch.Sw.Info);
            return DataXml;
        }

        /// <summary>
        /// Import into Crm ISV Datas from sent parameter
        /// </summary>
        public bool UpdateISVConfig(string newSiteMap,bool publish)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV UpdateISVConfig BEG publish: {0}.",publish),CRMTraceSwitch.Sw.Info);
            bool ret                                =   false;
            try
            {
                DataXml                             =   newSiteMap;
                if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV UpdateISVConfig DataXml: {0}.",DataXml),CRMTraceSwitch.Sw.Info);
                ImportExportXml ImportExportData    =   new ImportExportXml(ImportExportType.isvconfigxml,DataXml);
                ret                                 =   ImportExportData.Import(wrapper,publish);
                if ( !ret )
                    _errMsg                         =   ImportExportData.strErr;
            }
			catch (Exception ex)
			{
                if ( CRMTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmUtil4ISV UpdateISVConfig ex: {0}",ex),CRMTraceSwitch.Sw.Info);
                throw;
			}
             if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmUtil4ISV UpdateISVConfig END ret: {0}", ret),CRMTraceSwitch.Sw.Info);
            return ret;
        }

        #endregion public methods
    }
}